# app_gui.py —— 16bit 明文/密钥（4位十六进制），加解密 GUI（Tkinter）
import tkinter as tk
from tkinter import messagebox
import saes

def parse_hex4(s):
    x = int(s.strip(), 16)
    if not (0 <= x <= 0xFFFF):
        raise ValueError
    return x

def fmt(x): return f"{x:04X}"

def do_enc():
    try:
        p = parse_hex4(ent_p.get())
        k = parse_hex4(ent_k.get())
        c = saes.encrypt_block16(p, k)
        var_c.set(fmt(c))
    except Exception:
        messagebox.showerror("错误", "请输入4位十六进制，如 6F6B / 3A94")

def do_dec():
    try:
        c = parse_hex4(ent_c.get())
        k = parse_hex4(ent_k.get())
        p = saes.decrypt_block16(c, k)
        var_p.set(fmt(p))
    except Exception:
        messagebox.showerror("错误", "请输入4位十六进制，如 6F6B / 3A94")

root = tk.Tk()
root.title("S-AES 16-bit Demo")

var_p = tk.StringVar(value="0000")
var_k = tk.StringVar(value="0000")
var_c = tk.StringVar(value="0000")

tk.Label(root, text="明文 P (4hex)：").grid(row=0, column=0, sticky="e")
ent_p = tk.Entry(root, textvariable=var_p, width=8); ent_p.grid(row=0, column=1)

tk.Label(root, text="密钥 K (4hex)：").grid(row=1, column=0, sticky="e")
ent_k = tk.Entry(root, textvariable=var_k, width=8); ent_k.grid(row=1, column=1)

tk.Button(root, text="加密 →", command=do_enc).grid(row=2, column=0, pady=4)
tk.Button(root, text="← 解密", command=do_dec).grid(row=2, column=1, pady=4)

tk.Label(root, text="密文 C (4hex)：").grid(row=3, column=0, sticky="e")
ent_c = tk.Entry(root, textvariable=var_c, width=8); ent_c.grid(row=3, column=1)

root.mainloop()
